﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using System.Collections;

namespace ERPGoodsDelivery.Common
{
    /// <summary>
    /// 分组筛选
    /// </summary>
    public class GroupFilter
    {
        /// <summary>
        /// 根据分组得到分组内所有的元素
        /// </summary>
        /// <param name="view"></param>
        /// <param name="hitInfo"></param>
        /// <param name="src"></param>
        /// <returns></returns>
        public DataRow[] GetGroupRows(DevExpress.XtraGrid.Views.Grid.GridView view, int startRowindex, DataTable src)
        {
            //1取得所有分组
            DevExpress.XtraGrid.Columns.GridColumnReadOnlyCollection totalColumn = view.GroupedColumns;
            //2检索出有效的分组(因为拖曳操作可能是从多级分组中的任何一级执行)
            List<DevExpress.XtraGrid.Columns.GridColumn> validColumn = new List<DevExpress.XtraGrid.Columns.GridColumn>();
            string startColDisplay = view.GetGroupRowDisplayText(startRowindex); //组的显示内容
            string startCaption = startColDisplay.Substring(0, startColDisplay.IndexOf(":"));       //组的caption
            foreach (DevExpress.XtraGrid.Columns.GridColumn column in totalColumn)
            {
                validColumn.Insert(0, column);               //按分类从小到大的顺序
                if (column.Caption == startCaption)
                {
                    break;
                }
            }
            //循环行，得到检索条件键值对
            List<KeyValuePair<string, string>> results = new List<KeyValuePair<string, string>>();          //分组的条件集合
            string colDisplay = "";                         //组的显示字符串
            string colCaption = "";                         //组的caption
            int groupIndex = 0;
            DevExpress.XtraGrid.Columns.GridColumn currentGroup = validColumn[groupIndex];

            for (int i = startRowindex; i < 0; i++)
            {
                colDisplay = view.GetGroupRowDisplayText(i);
                colCaption = colDisplay.Substring(0, colDisplay.IndexOf(":"));
                if (colCaption == currentGroup.Caption)
                {
                    results.Add(new KeyValuePair<string, string>(currentGroup.FieldName, view.GetGroupRowValue(i).ToString()));
                    if (groupIndex == validColumn.Count - 1)
                    {
                        break;
                    }
                    groupIndex++;
                    currentGroup = validColumn[groupIndex];     //下一级分组条件
                }
            }
            //根据分组条件筛选数据集
            string selectStr = "1=1";
            foreach (KeyValuePair<string, string> pair in results)
            {
                selectStr += " and " + pair.Key + " ='" + pair.Value + "'";
            }
            DataRow[] rows = src.Select(selectStr);
            return rows;
        }
    }
}
